import requests
import json
import os
from urllib.parse import  urlencode

#伪装浏览器
header={
     'Host': 'so.toutiao.com',
     'Referer':'https://so.toutiao.com/search?keyword=%E8%A1%97%E6%8B%8D&pd=atlas&source=search_subtab_switch&dvpf=pc&aid=4916&page_num=0',
     'User-Agent':'Chrome/98.0.4750.0 Safari/537.36',

}
#经过发现cookie当中两条数据是变化的，但ttwid是最主要的
cookie={
        'ttwid':'1%7C5_2kPHbjq7j8rZDt3D9G8CPzKQnT6YQvSw_iaRUZZf4%7C1645576480%7C7f3bee63dacf8370a177ff30af7f62e61c7f16808a223fb7482772a916a52292', #变化
        # '_S_WIN_WH':'1366_663'#变化
}

#创建文件夹
pathd=os.getcwd()+'\\picture'
#判断mydata文件夹是否存在
if os.path.exists(pathd):
    pass
else:
    #创建mydata文件夹
    os.mkdir(pathd)

def main():
    values = {'keyword': '街拍'}
    values1= urlencode(values)#编码
    page_num=eval(input('请输入页数:'))
    for j in range(0,page_num):
        url = 'https://so.toutiao.com/search?{}&pd=atlas&source=search_subtab_switch&dvpf=pc&aid=4916&page_num={}&rawJSON=1'.format(values1,str(j))
        # print(url)
        red=requests.session()
        response=red.get(url,headers=header,cookies=cookie)
        #a=response.text
        a=json.loads(response.content)
        urll=a['rawData']['data']
        for i in range(len(urll)):
            image_url=urll[i]['img_url']
            # print(image_url)
            #下载图片
            pic=requests.get(image_url)
            with open('./picture/'+str(j)+str(i)+'.jpg','wb+') as f:
                f.write(pic.content)


if __name__=='__main__':
    main()

